package com.pai4j.zwiki.service.agent;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pai4j.zwiki.domain.entity.CodeStructureEntity;
import com.pai4j.zwiki.repository.CodeStructureRepository;
import com.pai4j.zwiki.service.LLMService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 代码阅读 Agent
 * 实现多轮深度代码阅读与分析
 * 
 * 功能：
 * 1. 多轮迭代式代码阅读
 * 2. 深度理解代码逻辑和架构
 * 3. 生成详细的分析报告
 * 4. 识别设计模式和最佳实践
 * 5. 分析代码质量和潜在问题
 *
 * @author pai4j
 * @since 2025-10-12
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CodeReadingAgent {

    private final CodeStructureRepository codeStructureRepository;
    private final LLMService llmService;
    private final DeepCodeReader deepCodeReader;
    private final CodeInsightAnalyzer codeInsightAnalyzer;
    private final IntelligentDocumentGenerator documentGenerator;
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 执行多轮代码阅读分析（优化版 - 渐进式理解）
     * 
     * 优化策略：
     * 1. 遵循"文档→配置→代码→综合"的渐进式理解顺序
     * 2. 每轮分析都传递前面的上下文，让大模型建立连贯理解
     * 3. 深度代码阅读前置，为后续分析提供充分的代码理解基础
     * 4. 各分析器之间传递分析结果，避免信息孤岛
     * 
     * @param taskId 任务ID
     * @param workspacePath 工作目录
     * @return 完整的分析报告
     */
    public Map<String, Object> executeDeepReading(String taskId, String workspacePath) {
        log.info("开始执行深度代码阅读（优化版-渐进式理解）, 任务ID: {}", taskId);

        Map<String, Object> report = new HashMap<>();
        StringBuilder contextBuilder = new StringBuilder(); // 构建累积上下文
        
        try {
            // ========== 阶段一：建立初步认知（文档和配置层） ==========
            
            // 第一轮：深度逐文件阅读（前置！先让大模型深度理解代码）
            log.info("【阶段一】第1轮：深度逐文件阅读（文档、配置、核心代码）");
            Map<String, Object> deepReadingReport = deepCodeReader.executeDeepReading(workspacePath, taskId);
            report.put("deepReadingReport", deepReadingReport);
            
            // 提取关键信息作为后续上下文
            String deepReadingContext = buildContextFromDeepReading(deepReadingReport);
            contextBuilder.append("## 深度代码阅读理解\n").append(deepReadingContext).append("\n\n");
            log.info("已完成深度代码阅读，建立了初步代码理解，上下文长度: {} 字符", deepReadingContext.length());

            // 第二轮：项目概览分析（基于深度阅读的理解）
            log.info("【阶段一】第2轮：项目概览分析（结合深度阅读理解）");
            Map<String, Object> overview = analyzeProjectOverviewWithContext(taskId, workspacePath, contextBuilder.toString());
            report.put("overview", overview);
            
            // 更新上下文
            if (overview.containsKey("llmSummary")) {
                contextBuilder.append("## 项目概览\n").append(overview.get("llmSummary")).append("\n\n");
            }

            // 第三轮：技术栈分析（基于已有理解）
            log.info("【阶段一】第3轮：技术栈分析");
            Map<String, Object> techStack = analyzeTechStackWithContext(workspacePath, contextBuilder.toString());
            report.put("techStack", techStack);
            
            if (techStack.containsKey("frameworks")) {
                contextBuilder.append("## 技术栈\n").append(techStack.get("frameworks")).append("\n\n");
            }

            // ========== 阶段二：深度理解（架构和设计层） ==========
            
            // 第四轮：核心模块分析（传递上下文）
            log.info("【阶段二】第4轮：核心模块分析（基于完整上下文）");
            List<Map<String, Object>> coreModules = analyzeCoreModulesWithContext(taskId, workspacePath, contextBuilder.toString());
            report.put("coreModules", coreModules);

            // 第五轮：依赖关系分析
            log.info("【阶段二】第5轮：依赖关系分析");
            Map<String, Object> dependencies = analyzeDependencies(taskId);
            report.put("dependencies", dependencies);

            // 第六轮：设计模式识别
            log.info("【阶段二】第6轮：设计模式识别");
            List<Map<String, Object>> patterns = identifyDesignPatterns(taskId, workspacePath);
            report.put("designPatterns", patterns);

            // ========== 阶段三：质量与洞察分析 ==========
            
            // 第七轮：代码洞察分析（传递深度阅读结果）
            log.info("【阶段三】第7轮：代码洞察分析（基于深度阅读和架构理解）");
            Map<String, Object> insightsReport = codeInsightAnalyzer.analyzeCodeInsightsWithContext(
                taskId, workspacePath, deepReadingReport, report
            );
            report.put("insightsReport", insightsReport);

            // 第八轮：代码质量分析
            log.info("【阶段三】第8轮：代码质量分析");
            Map<String, Object> quality = analyzeCodeQuality(taskId, workspacePath);
            report.put("quality", quality);

            // 第九轮：业务流程分析
            log.info("【阶段三】第9轮：业务流程分析");
            List<Map<String, Object>> flows = analyzeBusinessFlows(taskId, workspacePath);
            report.put("businessFlows", flows);

            // ========== 阶段四：综合与文档生成 ==========
            
            // 第十轮：生成综合报告（基于所有分析结果）
            log.info("【阶段四】第10轮：生成综合报告");
            String comprehensiveReport = generateComprehensiveReportWithFullContext(report);
            report.put("comprehensiveReport", comprehensiveReport);

            // 第十一轮：生成智能文档集（基于完整的分析结果）
            log.info("【阶段四】第11轮：生成项目文档集");
            Map<String, String> documents = documentGenerator.generateCompleteDocumentation(
                    report, 
                    extractProjectName(workspacePath), 
                    workspacePath
            );
            report.put("generatedDocuments", documents);

            log.info("深度代码阅读完成（优化版），共11轮分析，4个阶段");
            return report;

        } catch (Exception e) {
            log.error("深度代码阅读失败", e);
            report.put("error", e.getMessage());
            return report;
        }
    }

    /**
     * 第一轮：项目概览分析
     */
    private Map<String, Object> analyzeProjectOverview(String taskId, String workspacePath) {
        Map<String, Object> overview = new HashMap<>();

        try {
            // 读取项目根目录文件
            Path projectPath = Paths.get(workspacePath);
            List<String> rootFiles = Files.list(projectPath)
                    .filter(Files::isRegularFile)
                    .map(p -> p.getFileName().toString())
                    .collect(Collectors.toList());

            overview.put("rootFiles", rootFiles);

            // 检测项目类型
            String projectType = detectProjectType(rootFiles);
            overview.put("projectType", projectType);

            // 读取 README
            String readme = readFileIfExists(projectPath.resolve("README.md"));
            overview.put("readme", readme);

            // 获取代码结构统计
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);
            
            // 统计包分布
            Map<String, Long> packageDistribution = structures.stream()
                    .filter(s -> s.getPackageName() != null)
                    .collect(Collectors.groupingBy(
                            CodeStructureEntity::getPackageName,
                            Collectors.counting()
                    ));
            overview.put("packageDistribution", packageDistribution);

            // 统计类型分布
            Map<String, Long> typeDistribution = structures.stream()
                    .collect(Collectors.groupingBy(
                            CodeStructureEntity::getStructureType,
                            Collectors.counting()
                    ));
            overview.put("typeDistribution", typeDistribution);

            // 使用 LLM 生成项目概览总结
            String prompt = buildOverviewPrompt(overview);
            String llmSummary = llmService.generateCodeSummary(prompt);
            overview.put("llmSummary", llmSummary);

        } catch (Exception e) {
            log.error("项目概览分析失败", e);
            overview.put("error", e.getMessage());
        }

        return overview;
    }

    /**
     * 第二轮：核心模块分析
     */
    private List<Map<String, Object>> analyzeCoreModules(String taskId, String workspacePath) {
        List<Map<String, Object>> modules = new ArrayList<>();

        try {
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            // 识别核心包（代码最多的前10个包） - 增加分析范围以获得更完整的理解
            Map<String, List<CodeStructureEntity>> packageGroups = structures.stream()
                    .filter(s -> s.getPackageName() != null)
                    .collect(Collectors.groupingBy(CodeStructureEntity::getPackageName));

            List<String> corePackages = packageGroups.entrySet().stream()
                    .sorted((e1, e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size()))
                    .limit(10) // 增加到10个核心包
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());

            // 分析每个核心包
            for (String packageName : corePackages) {
                Map<String, Object> moduleAnalysis = analyzeModule(packageName, packageGroups.get(packageName), workspacePath);
                modules.add(moduleAnalysis);
            }

        } catch (Exception e) {
            log.error("核心模块分析失败", e);
        }

        return modules;
    }

    /**
     * 分析单个模块
     */
    private Map<String, Object> analyzeModule(String packageName, List<CodeStructureEntity> classes, String workspacePath) {
        Map<String, Object> analysis = new HashMap<>();
        analysis.put("packageName", packageName);
        analysis.put("classCount", classes.size());

        // 识别模块类型
        String moduleType = identifyModuleType(packageName, classes);
        analysis.put("moduleType", moduleType);

        // 提取关键类
        List<Map<String, String>> keyClasses = classes.stream()
                .limit(10)
                .map(c -> {
                    Map<String, String> info = new HashMap<>();
                    info.put("name", c.getName());
                    info.put("type", c.getStructureType());
                    info.put("modifier", c.getAccessModifier());
                    return info;
                })
                .collect(Collectors.toList());
        analysis.put("keyClasses", keyClasses);

        // 读取核心类的源码并让 LLM 分析
        try {
            if (!classes.isEmpty()) {
                CodeStructureEntity mainClass = classes.get(0);
                String sourceCode = readFileIfExists(Paths.get(mainClass.getFilePath()));
                
                if (sourceCode != null && !sourceCode.isEmpty()) {
                    // 传递更完整的代码给大模型，以便更准确地理解
                    String codeToAnalyze = sourceCode.length() > 30000 
                        ? sourceCode.substring(0, 30000) + "\n// ... 代码较长，已截取前30000字符"
                        : sourceCode;
                    
                    String prompt = String.format("""
                            请分析以下模块的核心类代码，说明其主要职责和功能：
                            
                            模块包名：%s
                            类名：%s
                            代码大小：%d 字符
                            
                            代码：
                            ```java
                            %s
                            ```
                            
                            请详细说明：
                            1. 该类的主要职责和在系统中的角色
                            2. 实现的核心功能和关键方法
                            3. 使用的关键技术和设计模式
                            4. 这个类体现的架构设计思想
                            5. 代码质量评价和改进建议
                            
                            请详细分析（500-800字）。
                            """, packageName, mainClass.getName(), sourceCode.length(), codeToAnalyze);
                    
                    String llmAnalysis = llmService.generateCodeSummary(prompt);
                    analysis.put("llmAnalysis", llmAnalysis);
                }
            }
        } catch (Exception e) {
            log.warn("读取模块源码失败: {}", packageName, e);
        }

        return analysis;
    }

    /**
     * 第三轮：依赖关系分析
     */
    private Map<String, Object> analyzeDependencies(String taskId) {
        Map<String, Object> dependencies = new HashMap<>();

        try {
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            // 构建依赖关系图
            Map<String, List<String>> dependencyGraph = new HashMap<>();
            
            for (CodeStructureEntity structure : structures) {
                if (structure.getDependencies() != null) {
                    try {
                        @SuppressWarnings("unchecked")
                        List<String> deps = objectMapper.readValue(structure.getDependencies(), List.class);
                        if (!deps.isEmpty()) {
                            dependencyGraph.put(structure.getName(), deps);
                        }
                    } catch (Exception e) {
                        // 忽略解析错误
                    }
                }
            }

            dependencies.put("dependencyGraph", dependencyGraph);

            // 计算依赖度指标
            Map<String, Integer> inDegree = new HashMap<>();  // 被依赖次数
            Map<String, Integer> outDegree = new HashMap<>(); // 依赖其他类次数

            for (Map.Entry<String, List<String>> entry : dependencyGraph.entrySet()) {
                String className = entry.getKey();
                List<String> deps = entry.getValue();
                
                outDegree.put(className, deps.size());
                
                for (String dep : deps) {
                    inDegree.put(dep, inDegree.getOrDefault(dep, 0) + 1);
                }
            }

            // 找出最重要的类（被依赖最多）
            List<Map.Entry<String, Integer>> topClasses = inDegree.entrySet().stream()
                    .sorted((e1, e2) -> Integer.compare(e2.getValue(), e1.getValue()))
                    .limit(10)
                    .collect(Collectors.toList());

            List<Map<String, Object>> importantClasses = topClasses.stream()
                    .map(e -> {
                        Map<String, Object> info = new HashMap<>();
                        info.put("className", e.getKey());
                        info.put("dependencyCount", e.getValue());
                        return info;
                    })
                    .collect(Collectors.toList());

            dependencies.put("importantClasses", importantClasses);

        } catch (Exception e) {
            log.error("依赖关系分析失败", e);
        }

        return dependencies;
    }

    /**
     * 第四轮：设计模式识别
     */
    private List<Map<String, Object>> identifyDesignPatterns(String taskId, String workspacePath) {
        List<Map<String, Object>> patterns = new ArrayList<>();

        try {
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            // 识别 Singleton 模式
            patterns.addAll(identifySingletonPattern(structures));

            // 识别 Factory 模式
            patterns.addAll(identifyFactoryPattern(structures));

            // 识别 Strategy 模式
            patterns.addAll(identifyStrategyPattern(structures));

            // 识别 Observer 模式
            patterns.addAll(identifyObserverPattern(structures));

            // 识别 Builder 模式
            patterns.addAll(identifyBuilderPattern(structures));

        } catch (Exception e) {
            log.error("设计模式识别失败", e);
        }

        return patterns;
    }

    /**
     * 第五轮：代码质量分析
     */
    private Map<String, Object> analyzeCodeQuality(String taskId, String workspacePath) {
        Map<String, Object> quality = new HashMap<>();

        try {
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            // 计算平均代码行数
            double avgLines = structures.stream()
                    .filter(s -> s.getLineCount() != null)
                    .mapToInt(CodeStructureEntity::getLineCount)
                    .average()
                    .orElse(0.0);
            quality.put("averageClassLines", Math.round(avgLines));

            // 识别大类（超过500行）
            List<String> largeClasses = structures.stream()
                    .filter(s -> s.getLineCount() != null && s.getLineCount() > 500)
                    .map(s -> s.getName() + " (" + s.getLineCount() + " lines)")
                    .collect(Collectors.toList());
            quality.put("largeClasses", largeClasses);

            // 统计访问修饰符分布
            Map<String, Long> modifierDistribution = structures.stream()
                    .filter(s -> s.getAccessModifier() != null)
                    .collect(Collectors.groupingBy(
                            CodeStructureEntity::getAccessModifier,
                            Collectors.counting()
                    ));
            quality.put("modifierDistribution", modifierDistribution);

            // 评分
            int score = calculateQualityScore(quality);
            quality.put("qualityScore", score);

        } catch (Exception e) {
            log.error("代码质量分析失败", e);
        }

        return quality;
    }

    /**
     * 第六轮：业务流程分析
     */
    private List<Map<String, Object>> analyzeBusinessFlows(String taskId, String workspacePath) {
        List<Map<String, Object>> flows = new ArrayList<>();

        try {
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            // 识别 Controller 类（业务入口）
            List<CodeStructureEntity> controllers = structures.stream()
                    .filter(s -> s.getName().endsWith("Controller") || 
                               (s.getAnnotations() != null && s.getAnnotations().contains("RestController")))
                    .collect(Collectors.toList());

            for (CodeStructureEntity controller : controllers) {
                Map<String, Object> flow = new HashMap<>();
                flow.put("entryPoint", controller.getName());
                flow.put("package", controller.getPackageName());
                
                // 尝试追踪调用链
                List<String> callChain = traceCallChain(controller, structures);
                flow.put("callChain", callChain);
                
                flows.add(flow);
            }

        } catch (Exception e) {
            log.error("业务流程分析失败", e);
        }

        return flows;
    }

    /**
     * 第七轮：技术栈分析
     */
    private Map<String, Object> analyzeTechStack(String workspacePath) {
        Map<String, Object> techStack = new HashMap<>();

        try {
            Path projectPath = Paths.get(workspacePath);

            // 读取 pom.xml 识别依赖
            String pomContent = readFileIfExists(projectPath.resolve("pom.xml"));
            if (pomContent != null) {
                List<String> dependencies = extractDependencies(pomContent);
                techStack.put("mavenDependencies", dependencies);

                // 识别框架
                List<String> frameworks = identifyFrameworks(dependencies);
                techStack.put("frameworks", frameworks);
            }

            // 读取 application.yml 识别配置
            String appYml = readFileIfExists(projectPath.resolve("src/main/resources/application.yml"));
            if (appYml != null) {
                Map<String, Object> configs = extractConfigurations(appYml);
                techStack.put("configurations", configs);
            }

        } catch (Exception e) {
            log.error("技术栈分析失败", e);
        }

        return techStack;
    }

    /**
     * 第八轮：生成综合报告
     */
    private String generateComprehensiveReport(Map<String, Object> analysisResults) {
        StringBuilder report = new StringBuilder();

        report.append("# 项目深度分析报告\n\n");

        // 项目概览
        @SuppressWarnings("unchecked")
        Map<String, Object> overview = (Map<String, Object>) analysisResults.get("overview");
        if (overview != null) {
            report.append("## 1. 项目概览\n\n");
            report.append(overview.getOrDefault("llmSummary", "")).append("\n\n");
        }

        // 核心模块
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> modules = (List<Map<String, Object>>) analysisResults.get("coreModules");
        if (modules != null && !modules.isEmpty()) {
            report.append("## 2. 核心模块分析\n\n");
            for (Map<String, Object> module : modules) {
                report.append("### ").append(module.get("packageName")).append("\n");
                report.append("- 类型：").append(module.get("moduleType")).append("\n");
                report.append("- 类数量：").append(module.get("classCount")).append("\n");
                if (module.containsKey("llmAnalysis")) {
                    report.append("\n").append(module.get("llmAnalysis")).append("\n");
                }
                report.append("\n");
            }
        }

        // 设计模式
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> patterns = (List<Map<String, Object>>) analysisResults.get("designPatterns");
        if (patterns != null && !patterns.isEmpty()) {
            report.append("## 3. 设计模式识别\n\n");
            for (Map<String, Object> pattern : patterns) {
                report.append("- **").append(pattern.get("pattern")).append("**: ")
                      .append(pattern.get("description")).append("\n");
            }
            report.append("\n");
        }

        // 代码质量
        @SuppressWarnings("unchecked")
        Map<String, Object> quality = (Map<String, Object>) analysisResults.get("quality");
        if (quality != null) {
            report.append("## 4. 代码质量评估\n\n");
            report.append("- 质量评分：").append(quality.get("qualityScore")).append("/100\n");
            report.append("- 平均类行数：").append(quality.get("averageClassLines")).append("\n\n");
        }

        // 技术栈
        @SuppressWarnings("unchecked")
        Map<String, Object> techStack = (Map<String, Object>) analysisResults.get("techStack");
        if (techStack != null && techStack.containsKey("frameworks")) {
            report.append("## 5. 技术栈\n\n");
            @SuppressWarnings("unchecked")
            List<String> frameworks = (List<String>) techStack.get("frameworks");
            for (String framework : frameworks) {
                report.append("- ").append(framework).append("\n");
            }
            report.append("\n");
        }

        return report.toString();
    }

    // ========== 辅助方法 ==========

    private String detectProjectType(List<String> rootFiles) {
        if (rootFiles.contains("pom.xml")) return "Maven Project";
        if (rootFiles.contains("build.gradle")) return "Gradle Project";
        if (rootFiles.contains("package.json")) return "Node.js Project";
        return "Unknown";
    }

    private String readFileIfExists(Path filePath) {
        try {
            if (Files.exists(filePath)) {
                return Files.readString(filePath);
            }
        } catch (IOException e) {
            log.warn("读取文件失败: {}", filePath, e);
        }
        return null;
    }

    private String identifyModuleType(String packageName, List<CodeStructureEntity> classes) {
        String pkgLower = packageName.toLowerCase();
        if (pkgLower.contains("controller")) return "控制器层";
        if (pkgLower.contains("service")) return "服务层";
        if (pkgLower.contains("repository") || pkgLower.contains("dao")) return "数据访问层";
        if (pkgLower.contains("entity") || pkgLower.contains("domain")) return "领域模型层";
        if (pkgLower.contains("config")) return "配置层";
        if (pkgLower.contains("util")) return "工具层";
        return "业务模块";
    }

    private List<Map<String, Object>> identifySingletonPattern(List<CodeStructureEntity> structures) {
        // 简化实现：查找包含 "getInstance" 的类
        return structures.stream()
                .filter(s -> s.getName().contains("Singleton") || s.getName().contains("Instance"))
                .map(s -> {
                    Map<String, Object> pattern = new HashMap<>();
                    pattern.put("pattern", "Singleton");
                    pattern.put("class", s.getName());
                    pattern.put("description", "单例模式 - 确保一个类只有一个实例");
                    return pattern;
                })
                .collect(Collectors.toList());
    }

    private List<Map<String, Object>> identifyFactoryPattern(List<CodeStructureEntity> structures) {
        return structures.stream()
                .filter(s -> s.getName().endsWith("Factory"))
                .map(s -> {
                    Map<String, Object> pattern = new HashMap<>();
                    pattern.put("pattern", "Factory");
                    pattern.put("class", s.getName());
                    pattern.put("description", "工厂模式 - 创建对象的接口");
                    return pattern;
                })
                .collect(Collectors.toList());
    }

    private List<Map<String, Object>> identifyStrategyPattern(List<CodeStructureEntity> structures) {
        return structures.stream()
                .filter(s -> s.getName().endsWith("Strategy"))
                .map(s -> {
                    Map<String, Object> pattern = new HashMap<>();
                    pattern.put("pattern", "Strategy");
                    pattern.put("class", s.getName());
                    pattern.put("description", "策略模式 - 定义一系列算法");
                    return pattern;
                })
                .collect(Collectors.toList());
    }

    private List<Map<String, Object>> identifyObserverPattern(List<CodeStructureEntity> structures) {
        return structures.stream()
                .filter(s -> s.getName().contains("Observer") || s.getName().contains("Listener"))
                .map(s -> {
                    Map<String, Object> pattern = new HashMap<>();
                    pattern.put("pattern", "Observer");
                    pattern.put("class", s.getName());
                    pattern.put("description", "观察者模式 - 对象间的一对多依赖");
                    return pattern;
                })
                .collect(Collectors.toList());
    }

    private List<Map<String, Object>> identifyBuilderPattern(List<CodeStructureEntity> structures) {
        return structures.stream()
                .filter(s -> s.getName().endsWith("Builder"))
                .map(s -> {
                    Map<String, Object> pattern = new HashMap<>();
                    pattern.put("pattern", "Builder");
                    pattern.put("class", s.getName());
                    pattern.put("description", "建造者模式 - 构建复杂对象");
                    return pattern;
                })
                .collect(Collectors.toList());
    }

    private int calculateQualityScore(Map<String, Object> quality) {
        int score = 100;
        
        // 大类扣分
        @SuppressWarnings("unchecked")
        List<String> largeClasses = (List<String>) quality.get("largeClasses");
        if (largeClasses != null) {
            score -= largeClasses.size() * 5;
        }
        
        // 平均行数
        Object avgLines = quality.get("averageClassLines");
        if (avgLines != null && ((Number) avgLines).intValue() > 300) {
            score -= 10;
        }
        
        return Math.max(0, Math.min(100, score));
    }

    private List<String> traceCallChain(CodeStructureEntity entry, List<CodeStructureEntity> allClasses) {
        List<String> chain = new ArrayList<>();
        chain.add(entry.getName());
        
        // 简化实现：只追踪一层
        if (entry.getDependencies() != null) {
            try {
                @SuppressWarnings("unchecked")
                List<String> deps = objectMapper.readValue(entry.getDependencies(), List.class);
                chain.addAll(deps.stream().limit(3).collect(Collectors.toList()));
            } catch (Exception e) {
                // 忽略
            }
        }
        
        return chain;
    }

    private List<String> extractDependencies(String pomContent) {
        List<String> deps = new ArrayList<>();
        // 简单的正则匹配
        String[] lines = pomContent.split("\n");
        for (String line : lines) {
            if (line.trim().startsWith("<artifactId>") && line.contains("</artifactId>")) {
                String dep = line.replaceAll("</?artifactId>", "").trim();
                deps.add(dep);
            }
        }
        return deps;
    }

    private List<String> identifyFrameworks(List<String> dependencies) {
        List<String> frameworks = new ArrayList<>();
        
        for (String dep : dependencies) {
            if (dep.contains("spring-boot")) frameworks.add("Spring Boot");
            if (dep.contains("spring-cloud")) frameworks.add("Spring Cloud");
            if (dep.contains("mybatis")) frameworks.add("MyBatis");
            if (dep.contains("redis")) frameworks.add("Redis");
            if (dep.contains("mysql")) frameworks.add("MySQL");
        }
        
        return frameworks.stream().distinct().collect(Collectors.toList());
    }

    private Map<String, Object> extractConfigurations(String ymlContent) {
        Map<String, Object> configs = new HashMap<>();
        
        if (ymlContent.contains("spring.datasource")) {
            configs.put("database", "已配置数据源");
        }
        if (ymlContent.contains("redis")) {
            configs.put("cache", "已配置Redis缓存");
        }
        if (ymlContent.contains("rocketmq")) {
            configs.put("mq", "已配置RocketMQ消息队列");
        }
        
        return configs;
    }

    private String buildOverviewPrompt(Map<String, Object> overview) {
        return String.format("""
                项目类型：%s
                包分布：%s
                类型分布：%s
                
                请生成一个简洁的项目概览总结。
                """,
                overview.getOrDefault("projectType", "未知"),
                overview.getOrDefault("packageDistribution", new HashMap<>()),
                overview.getOrDefault("typeDistribution", new HashMap<>())
        );
    }

    /**
     * 从工作目录路径提取项目名称
     */
    private String extractProjectName(String workspacePath) {
        Path path = Paths.get(workspacePath);
        return path.getFileName().toString();
    }

    // ========== 优化的上下文传递方法 ==========

    /**
     * 从深度阅读结果中提取关键信息构建上下文
     * 这个上下文将传递给后续的所有分析，让大模型建立连贯的理解
     */
    private String buildContextFromDeepReading(Map<String, Object> deepReadingReport) {
        StringBuilder context = new StringBuilder();
        
        try {
            // 提取文档分析
            @SuppressWarnings("unchecked")
            Map<String, String> docs = (Map<String, String>) deepReadingReport.get("documentAnalysis");
            if (docs != null && !docs.isEmpty()) {
                context.append("### 项目文档理解\n");
                docs.forEach((file, analysis) -> {
                    context.append("**").append(file).append("**: ")
                           .append(truncateContext(analysis, 300)).append("\n");
                });
                context.append("\n");
            }

            // 提取配置分析
            @SuppressWarnings("unchecked")
            Map<String, String> configs = (Map<String, String>) deepReadingReport.get("configAnalysis");
            if (configs != null && !configs.isEmpty()) {
                context.append("### 配置文件理解\n");
                configs.forEach((file, analysis) -> {
                    context.append("**").append(file).append("**: ")
                           .append(truncateContext(analysis, 200)).append("\n");
                });
                context.append("\n");
            }

            // 提取核心文件分析摘要
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> coreFiles = (List<Map<String, Object>>) deepReadingReport.get("coreFilesAnalysis");
            if (coreFiles != null && !coreFiles.isEmpty()) {
                context.append("### 核心代码文件理解\n");
                for (int i = 0; i < Math.min(5, coreFiles.size()); i++) {
                    Map<String, Object> file = coreFiles.get(i);
                    context.append("**").append(file.get("fileName")).append("**: ");
                    Object analysis = file.get("fileAnalysis");
                    if (analysis != null) {
                        context.append(truncateContext(analysis.toString(), 250)).append("\n");
                    }
                }
                context.append("\n");
            }

            // 提取综合理解
            String comprehensiveUnderstanding = (String) deepReadingReport.get("comprehensiveUnderstanding");
            if (comprehensiveUnderstanding != null && !comprehensiveUnderstanding.isEmpty()) {
                context.append("### 项目综合理解\n");
                context.append(truncateContext(comprehensiveUnderstanding, 500)).append("\n\n");
            }

        } catch (Exception e) {
            log.warn("构建深度阅读上下文时出错", e);
        }

        return context.toString();
    }

    /**
     * 带上下文的项目概览分析
     * 基于深度代码阅读的理解，进行更准确的概览分析
     */
    private Map<String, Object> analyzeProjectOverviewWithContext(String taskId, String workspacePath, String context) {
        Map<String, Object> overview = new HashMap<>();

        try {
            // 读取项目根目录文件
            Path projectPath = Paths.get(workspacePath);
            List<String> rootFiles = Files.list(projectPath)
                    .filter(Files::isRegularFile)
                    .map(p -> p.getFileName().toString())
                    .collect(Collectors.toList());

            overview.put("rootFiles", rootFiles);

            // 检测项目类型
            String projectType = detectProjectType(rootFiles);
            overview.put("projectType", projectType);

            // 读取 README
            String readme = readFileIfExists(projectPath.resolve("README.md"));
            overview.put("readme", readme);

            // 获取代码结构统计
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);
            
            // 统计包分布
            Map<String, Long> packageDistribution = structures.stream()
                    .filter(s -> s.getPackageName() != null)
                    .collect(Collectors.groupingBy(
                            CodeStructureEntity::getPackageName,
                            Collectors.counting()
                    ));
            overview.put("packageDistribution", packageDistribution);

            // 统计类型分布
            Map<String, Long> typeDistribution = structures.stream()
                    .collect(Collectors.groupingBy(
                            CodeStructureEntity::getStructureType,
                            Collectors.counting()
                    ));
            overview.put("typeDistribution", typeDistribution);

            // 使用 LLM 生成项目概览总结（传递深度阅读的上下文）
            String prompt = buildOverviewPromptWithContext(overview, context);
            String llmSummary = llmService.generateCodeSummary(prompt);
            overview.put("llmSummary", llmSummary);

        } catch (Exception e) {
            log.error("项目概览分析失败", e);
            overview.put("error", e.getMessage());
        }

        return overview;
    }

    /**
     * 构建带上下文的概览提示词
     */
    private String buildOverviewPromptWithContext(Map<String, Object> overview, String context) {
        return String.format("""
                你已经完成了对项目代码的深度阅读，获得了以下理解：
                
                %s
                
                现在，基于这些深度理解，请生成项目的整体概览总结：
                
                项目类型：%s
                包分布：%s
                类型分布：%s
                
                请结合你对代码的深度理解，生成一个全面、准确的项目概览（500-800字），包括：
                1. 项目的核心定位和价值
                2. 主要功能和特性
                3. 技术架构特点
                4. 适用场景
                5. 项目亮点
                """,
                truncateContext(context, 2000),
                overview.getOrDefault("projectType", "未知"),
                overview.getOrDefault("packageDistribution", new HashMap<>()),
                overview.getOrDefault("typeDistribution", new HashMap<>())
        );
    }

    /**
     * 带上下文的技术栈分析
     */
    private Map<String, Object> analyzeTechStackWithContext(String workspacePath, String context) {
        Map<String, Object> techStack = new HashMap<>();

        try {
            Path projectPath = Paths.get(workspacePath);

            // 读取 pom.xml 识别依赖
            String pomContent = readFileIfExists(projectPath.resolve("pom.xml"));
            if (pomContent != null) {
                List<String> dependencies = extractDependencies(pomContent);
                techStack.put("mavenDependencies", dependencies);

                // 识别框架
                List<String> frameworks = identifyFrameworks(dependencies);
                techStack.put("frameworks", frameworks);
                
                // 使用LLM分析技术栈（传递上下文）
                String prompt = String.format("""
                        基于对项目的深度理解：
                        
                        %s
                        
                        项目使用了以下技术依赖：
                        %s
                        
                        请详细分析：
                        1. 这些技术选型的合理性
                        2. 技术栈的搭配是否合理
                        3. 与项目业务需求的匹配度
                        4. 可能存在的技术债务或改进空间
                        
                        请详细分析（400-600字）。
                        """,
                        truncateContext(context, 1500),
                        String.join(", ", dependencies)
                );
                String techAnalysis = llmService.generateCodeSummary(prompt);
                techStack.put("llmTechAnalysis", techAnalysis);
            }

            // 读取 application.yml 识别配置
            String appYml = readFileIfExists(projectPath.resolve("src/main/resources/application.yml"));
            if (appYml != null) {
                Map<String, Object> configs = extractConfigurations(appYml);
                techStack.put("configurations", configs);
            }

        } catch (Exception e) {
            log.error("技术栈分析失败", e);
        }

        return techStack;
    }

    /**
     * 带上下文的核心模块分析
     */
    private List<Map<String, Object>> analyzeCoreModulesWithContext(String taskId, String workspacePath, String context) {
        List<Map<String, Object>> modules = new ArrayList<>();

        try {
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            // 识别核心包（代码最多的前10个包） - 增加分析范围以获得更完整的理解
            Map<String, List<CodeStructureEntity>> packageGroups = structures.stream()
                    .filter(s -> s.getPackageName() != null)
                    .collect(Collectors.groupingBy(CodeStructureEntity::getPackageName));

            List<String> corePackages = packageGroups.entrySet().stream()
                    .sorted((e1, e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size()))
                    .limit(10) // 增加到10个核心包
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());

            // 分析每个核心包（传递上下文）
            for (String packageName : corePackages) {
                Map<String, Object> moduleAnalysis = analyzeModuleWithContext(
                    packageName, packageGroups.get(packageName), workspacePath, context
                );
                modules.add(moduleAnalysis);
            }

        } catch (Exception e) {
            log.error("核心模块分析失败", e);
        }

        return modules;
    }

    /**
     * 带上下文的模块分析
     */
    private Map<String, Object> analyzeModuleWithContext(String packageName, List<CodeStructureEntity> classes, 
                                                          String workspacePath, String context) {
        Map<String, Object> analysis = new HashMap<>();
        analysis.put("packageName", packageName);
        analysis.put("classCount", classes.size());

        // 识别模块类型
        String moduleType = identifyModuleType(packageName, classes);
        analysis.put("moduleType", moduleType);

        // 提取关键类
        List<Map<String, String>> keyClasses = classes.stream()
                .limit(10)
                .map(c -> {
                    Map<String, String> info = new HashMap<>();
                    info.put("name", c.getName());
                    info.put("type", c.getStructureType());
                    info.put("modifier", c.getAccessModifier());
                    return info;
                })
                .collect(Collectors.toList());
        analysis.put("keyClasses", keyClasses);

        // 读取核心类的源码并让 LLM 分析（传递完整上下文）
        try {
            if (!classes.isEmpty()) {
                CodeStructureEntity mainClass = classes.get(0);
                String sourceCode = readFileIfExists(Paths.get(mainClass.getFilePath()));
                
                if (sourceCode != null && !sourceCode.isEmpty()) {
                    // 传递更完整的代码给大模型，以便更准确地理解
                    String codeToAnalyze = sourceCode.length() > 30000 
                        ? sourceCode.substring(0, 30000) + "\n// ... 代码较长，已截取前30000字符"
                        : sourceCode;
                    
                    String prompt = String.format("""
                            基于对整个项目的深度理解：
                            
                            %s
                            
                            现在分析以下模块的核心类：
                            
                            模块包名：%s
                            模块类型：%s
                            类名：%s
                            代码大小：%d 字符
                            
                            代码：
                            ```java
                            %s
                            ```
                            
                            请基于完整的项目理解，详细说明：
                            1. 该类在整个项目架构中的位置和作用
                            2. 与其他模块的协作关系
                            3. 实现的核心功能和关键方法
                            4. 使用的关键技术和设计模式
                            5. 这个类体现的架构设计思想
                            6. 代码质量评价和改进建议
                            
                            请详细分析（600-1000字）。
                            """, 
                            truncateContext(context, 1500),
                            packageName, 
                            moduleType,
                            mainClass.getName(), 
                            sourceCode.length(), 
                            codeToAnalyze
                    );
                    
                    String llmAnalysis = llmService.generateCodeSummary(prompt);
                    analysis.put("llmAnalysis", llmAnalysis);
                }
            }
        } catch (Exception e) {
            log.warn("读取模块源码失败: {}", packageName, e);
        }

        return analysis;
    }

    /**
     * 带完整上下文的综合报告生成
     */
    private String generateComprehensiveReportWithFullContext(Map<String, Object> analysisResults) {
        StringBuilder report = new StringBuilder();

        report.append("# 项目深度分析报告（完整版）\n\n");
        report.append("> 本报告基于对项目代码的多轮深度分析生成\n\n");

        // 深度阅读理解
        @SuppressWarnings("unchecked")
        Map<String, Object> deepReading = (Map<String, Object>) analysisResults.get("deepReadingReport");
        if (deepReading != null && deepReading.containsKey("comprehensiveUnderstanding")) {
            report.append("## 一、项目深度理解\n\n");
            report.append(deepReading.get("comprehensiveUnderstanding")).append("\n\n");
        }

        // 项目概览
        @SuppressWarnings("unchecked")
        Map<String, Object> overview = (Map<String, Object>) analysisResults.get("overview");
        if (overview != null && overview.containsKey("llmSummary")) {
            report.append("## 二、项目概览\n\n");
            report.append(overview.get("llmSummary")).append("\n\n");
        }

        // 技术栈分析
        @SuppressWarnings("unchecked")
        Map<String, Object> techStack = (Map<String, Object>) analysisResults.get("techStack");
        if (techStack != null) {
            report.append("## 三、技术栈分析\n\n");
            if (techStack.containsKey("llmTechAnalysis")) {
                report.append(techStack.get("llmTechAnalysis")).append("\n\n");
            }
            if (techStack.containsKey("frameworks")) {
                report.append("### 使用的框架\n");
                @SuppressWarnings("unchecked")
                List<String> frameworks = (List<String>) techStack.get("frameworks");
                for (String framework : frameworks) {
                    report.append("- ").append(framework).append("\n");
                }
                report.append("\n");
            }
        }

        // 核心模块
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> modules = (List<Map<String, Object>>) analysisResults.get("coreModules");
        if (modules != null && !modules.isEmpty()) {
            report.append("## 四、核心模块分析\n\n");
            for (Map<String, Object> module : modules) {
                report.append("### ").append(module.get("packageName")).append("\n");
                report.append("- 类型：").append(module.get("moduleType")).append("\n");
                report.append("- 类数量：").append(module.get("classCount")).append("\n");
                if (module.containsKey("llmAnalysis")) {
                    report.append("\n").append(module.get("llmAnalysis")).append("\n");
                }
                report.append("\n");
            }
        }

        // 设计模式
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> patterns = (List<Map<String, Object>>) analysisResults.get("designPatterns");
        if (patterns != null && !patterns.isEmpty()) {
            report.append("## 五、设计模式识别\n\n");
            for (Map<String, Object> pattern : patterns) {
                report.append("- **").append(pattern.get("pattern")).append("**: ")
                      .append(pattern.get("description")).append("\n");
            }
            report.append("\n");
        }

        // 代码洞察
        @SuppressWarnings("unchecked")
        Map<String, Object> insights = (Map<String, Object>) analysisResults.get("insightsReport");
        if (insights != null) {
            report.append("## 六、代码洞察分析\n\n");
            
            // 架构模式
            @SuppressWarnings("unchecked")
            Map<String, Object> archPatterns = (Map<String, Object>) insights.get("architecturePatterns");
            if (archPatterns != null && archPatterns.containsKey("llmArchitectureAnalysis")) {
                report.append("### 架构分析\n\n");
                report.append(archPatterns.get("llmArchitectureAnalysis")).append("\n\n");
            }

            // 技术债务
            @SuppressWarnings("unchecked")
            Map<String, Object> debt = (Map<String, Object>) insights.get("technicalDebt");
            if (debt != null && debt.containsKey("debtLevel")) {
                report.append("### 技术债务评估\n\n");
                report.append("- 技术债务等级：").append(debt.get("debtLevel")).append("\n");
                report.append("- 债务项数量：").append(debt.getOrDefault("totalDebtItems", 0)).append("\n\n");
            }
        }

        // 代码质量
        @SuppressWarnings("unchecked")
        Map<String, Object> quality = (Map<String, Object>) analysisResults.get("quality");
        if (quality != null) {
            report.append("## 七、代码质量评估\n\n");
            report.append("- 质量评分：").append(quality.get("qualityScore")).append("/100\n");
            report.append("- 平均类行数：").append(quality.get("averageClassLines")).append("\n\n");
        }

        // 改进建议
        if (insights != null && insights.containsKey("improvementRoadmap")) {
            report.append("## 八、改进路线图\n\n");
            report.append(insights.get("improvementRoadmap")).append("\n\n");
        }

        return report.toString();
    }

    /**
     * 截断上下文文本
     */
    private String truncateContext(String text, int maxLength) {
        if (text == null) return "";
        if (text.length() <= maxLength) return text;
        return text.substring(0, maxLength) + "...";
    }
}

